package com.dynamic.model.util.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;


public class Signature
{
    public static String getSign(Map<String, Object> map, String key)
    {
        ArrayList list = new ArrayList();
        for (Map.Entry entry : map.entrySet()) {
            if (entry.getValue() != "") {
                list.add((String)entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String[] arrayToSort = (String[])list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result = result + "key=" + key;

        result = Md5Util.MD5(result).toUpperCase();

        return result;
    }

    public static String getSignFromResponseString(String responseString, String key)
            throws IOException, SAXException, ParserConfigurationException
    {
        Map map = XMLParser.getMapFromXML(responseString);

        map.put("sign", "");
        map.put("sign", getSign(map, key));

        return XMLTools.mapToXml(map);
    }
}
